package com.liam.unit.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by liam on 16/10/20.
 */
public class HttpUtil {

    private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class.getCanonicalName());

    public static JSONObject httpGet(String url) throws Exception {
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = MyHttpClientUtils.getHttpClient();
        RequestConfig requestConfig = RequestConfig.custom().
                setSocketTimeout(2000).setConnectTimeout(2000).build();
        httpGet.setConfig(requestConfig);

        try {
            response = httpClient.execute(httpGet, new BasicHttpContext());

            if (response.getStatusLine().getStatusCode() != 200) {

                logger.debug("request url failed, http code=" + response.getStatusLine().getStatusCode()
                        + ", url=" + url);
                return null;
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String resultStr = EntityUtils.toString(entity, "utf-8");

                return JSON.parseObject(resultStr);

            }
        } catch (IOException e) {
            logger.debug("request url=" + url + ", exception, msg=" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (response != null) try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }


    public static JSONObject httpPost(String url, Object data,String contentType) throws IOException {
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = MyHttpClientUtils.getHttpClient();//modify by neo 2016.10.26
        RequestConfig requestConfig = RequestConfig.custom().
                setSocketTimeout(5000).setConnectTimeout(2000).build();
        httpPost.setConfig(requestConfig);

        httpPost.addHeader("Content-Type", "application/json");
        if(StringUtils.isNotBlank(contentType)){
            httpPost.addHeader("Content-Type", contentType);
        }
        try {
            StringEntity requestEntity = new StringEntity(JSON.toJSONString(data), "utf-8");
            httpPost.setEntity(requestEntity);

            response = httpClient.execute(httpPost, new BasicHttpContext());

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String resultStr = EntityUtils.toString(entity, "utf-8");

                return JSON.parseObject(resultStr);
            }
        } catch (IOException e) {
            logger.info("request url=" + url + ", exception, msg=" + e.getMessage());
            e.printStackTrace();
            throw e;
        } finally {
            if (response != null) try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    public static JSONObject httpPost(String url, Object data, String filePramName, MultipartFile file) throws IOException {
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = MyHttpClientUtils.getHttpClient();
        RequestConfig requestConfig = RequestConfig.custom().
                setSocketTimeout(5000).setConnectTimeout(2000).build();
        httpPost.setConfig(requestConfig);

//        httpPost.addHeader("Content-Type", "multipart/form-data"); 用MultipartEntityBuilder 时不能手动设定header
        try {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setCharset(Charset.forName("utf-8"));
//            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//加上此行代码解决返回中文乱码问题
            builder.addBinaryBody(filePramName, file.getBytes(), ContentType.MULTIPART_FORM_DATA, file.getName());// 文件流
            System.err.println(filePramName+","+file.getBytes());

            Map<String,String> otherParams = (Map<String, String>) data;
            for (Map.Entry<String, String> e : otherParams.entrySet()) {
                builder.addTextBody(e.getKey(), e.getValue());// 类似浏览器表单提交，对应input的name和value
            }
            HttpEntity entity = builder.build();

            httpPost.setEntity(entity);

            response = httpClient.execute(httpPost, new BasicHttpContext());

            entity = response.getEntity();
            if (entity != null) {
                String resultStr = EntityUtils.toString(entity, "utf-8");
                logger.info("http post > resultStr:{}",resultStr);
                return JSON.parseObject(resultStr);
            }
        } catch (IOException e) {
            logger.info("request url=" + url + ", exception, msg=" + e.getMessage());
            e.printStackTrace();
            throw e;
        } finally {
            if (response != null) try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    public static JSONObject httpPost(String url, Object data) throws IOException {
       return  httpPost(url,data,"");
    }

    /**
     * 获取response header中Content-Disposition中的filename值
     * @param response
     * @return
     */
    public static String getFileName(HttpResponse response) {
        Header contentHeader = response.getFirstHeader("Content-Disposition");
        String filename = null;
        if (contentHeader != null) {
            HeaderElement[] values = contentHeader.getElements();
            if (values.length == 1) {
                NameValuePair param = values[0].getParameterByName("filename");
                if (param != null) {
                    try {
                        //filename = new String(param.getValue().toString().getBytes(), "utf-8");
                        //filename=URLDecoder.decode(param.getValue(),"utf-8");
                        filename = param.getValue();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return filename;
    }




    /*=========================   https取消验证  JDK8不可用 jdk7可以      ===============================*/
    private static DefaultHttpClient client;
    /**
     * 访问https的网站
     * @param httpclient
     */
    private static void enableSSL(DefaultHttpClient httpclient){
        //调用ssl
        try {
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, new TrustManager[] { truseAllManager }, null);
            SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            Scheme https = new Scheme("https", sf, 443);
            httpclient.getConnectionManager().getSchemeRegistry().register(https);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 重写验证方法，取消检测ssl
     */
    private static TrustManager truseAllManager = new X509TrustManager(){

        public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException {}

        public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException {}

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

    };
    /**
     * HTTP Client Object,used HttpClient Class before(version 3.x),but now the
     * HttpClient is an interface
     */


    public static String sendXMLDataByGet(String url,String xml){
        // 创建HttpClient实例
        if (client == null) {
            client = new DefaultHttpClient();
            enableSSL(client);
        }
        StringBuilder urlString=new StringBuilder();
        urlString.append(url);
        urlString.append("?");
        logger.debug("getUTF8XMLString(xml):"+getUTF8XMLString(xml));
        try {
            urlString.append(URLEncoder.encode(getUTF8XMLString(xml), "UTF-8"));
        } catch (UnsupportedEncodingException e2) {
            e2.printStackTrace();
        }
        String urlReq=urlString.toString();
        // 创建Get方法实例
        HttpGet httpsgets = new HttpGet(urlReq);

        String strRep="";
        try {
            HttpResponse response = client.execute(httpsgets);
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                strRep = EntityUtils.toString(response.getEntity());
                // Do not need the rest
                httpsgets.abort();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return strRep;
    }


    /**
     * Send a XML-Formed string to HTTP Server by post method
     *
     * @param url
     *            the request URL string
     * @param xmlData
     *            XML-Formed string ,will not check whether this string is
     *            XML-Formed or not
     * @return the HTTP response status code ,like 200 represents OK,404 not
     *         found
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static String sendXMLDataByPost(String url, String xmlData)
            throws ClientProtocolException, IOException {
        if (client == null) {
            client = new DefaultHttpClient();
            enableSSL(client);
        }
        client.getParams().setParameter("http.protocol.content-charset",
                HTTP.UTF_8);
        client.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);
        client.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);
        client.getParams().setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET,
                HTTP.UTF_8);

        HttpPost post = new HttpPost(url);
        post.getParams().setParameter("http.protocol.content-charset",
                HTTP.UTF_8);
        post.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);
        post.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);
        post.getParams()
                .setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET, HTTP.UTF_8);


        StringEntity entity = new StringEntity(getUTF8XMLString(xmlData), "UTF-8");
        entity.setContentType("text/xml;charset=UTF-8");
        entity.setContentEncoding("UTF-8");
        // Set XML entity
        post.setEntity(entity);
        // Set content type of request header
        post.setHeader("Content-Type", "text/xml;charset=UTF-8");
        // Execute request and get the response
        HttpResponse response = client.execute(post);
        HttpEntity entityRep = response.getEntity();
        String strrep="";
        if (entityRep != null) {
            strrep = EntityUtils.toString(response.getEntity());
            // Do not need the rest
            post.abort();
        }
        // Response Header - StatusLine - status code
        // statusCode = response.getStatusLine().getStatusCode();
        return strrep;
    }
    /**
     * Get XML String of utf-8
     *
     * @return XML-Formed string
     */
    public static String getUTF8XMLString(String xml) {
        // A StringBuffer Object
        StringBuffer sb = new StringBuffer();
        sb.append(xml);
        String xmString = "";
        try {
            xmString = new String(sb.toString().getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return xmString.toString();
    }

    /**
     * 发送post请求
     *
     * @param url
     * @param map
     * @return 页面内容（html代码）
     */
    public static String sendDataByPost(String url, Map<String,String> map){
        if (client == null) {
            client = new DefaultHttpClient();
            enableSSL(client);
        }
        client.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8);
        client.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);
        client.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);
        client.getParams().setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET, HTTP.UTF_8);

        HttpPost httpPost = new HttpPost(url);
        httpPost.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8);
        httpPost.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);
        httpPost.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);
        httpPost.getParams().setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET, HTTP.UTF_8);


        //设置参数
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        Iterator iterator = map.entrySet().iterator();
        while(iterator.hasNext()){
            Map.Entry<String,String> elem = (Map.Entry<String, String>) iterator.next();
            list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));
        }
        String strrep="";
        try {
            if(list.size() > 0){
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,"UTF-8");
                httpPost.setEntity(entity);
            }

            // Execute request and get the response
            HttpResponse response = client.execute(httpPost);
            HttpEntity entityRep = response.getEntity();

            if (entityRep != null) {
                strrep = EntityUtils.toString(response.getEntity());
                // Do not need the rest
                httpPost.abort();
            }
        }catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // Response Header - StatusLine - status code
        // statusCode = response.getStatusLine().getStatusCode();
        return strrep;
    }

//=============================================================================================


    public static JSONObject get(String url) throws Exception {
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = MyHttpClientUtils.getHttpClient();
        RequestConfig requestConfig = RequestConfig.custom().
                setSocketTimeout(5000).setConnectTimeout(3000).build();
        httpGet.setConfig(requestConfig);
        try {
            //开始时间
            long startTime= System.currentTimeMillis();
            //执行请求
            try {
                response = httpClient.execute(httpGet, new BasicHttpContext());
            }catch (Exception e){
                logger.error("调用get请求失败,再次执行");
                response = httpClient.execute(httpGet, new BasicHttpContext());
            }
            //结束时间
            long endTime= System.currentTimeMillis();
            logger.debug(url+"请求耗时毫秒数："+(endTime-startTime)+",换算为秒："+(endTime-startTime)/1000f);
            //处理响应码
            if (response.getStatusLine().getStatusCode() != 200) {
                logger.debug("request url failed, http code=" + response.getStatusLine().getStatusCode() + ", url=" + url);
                return null;
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String resultStr = EntityUtils.toString(entity, "utf-8");

                logger.info("结果：{}",resultStr);
                return JSON.parseObject(resultStr);
            }
        } catch (IOException e) {
            logger.debug("request url=" + url + ", exception, msg=" + e.getMessage());
            e.printStackTrace();
            throw  e;
        } finally {
            if (response != null) try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    public static JSONArray getJsonArray(String url) throws Exception {
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = MyHttpClientUtils.getHttpClient();
        RequestConfig requestConfig = RequestConfig.custom().
                setSocketTimeout(5000).setConnectTimeout(3000).build();
        httpGet.setConfig(requestConfig);
        try {
            //开始时间
            long startTime= System.currentTimeMillis();
            //执行请求
            try {
                response = httpClient.execute(httpGet, new BasicHttpContext());
            }catch (Exception e){
                logger.error("调用get请求失败,再次执行");
                response = httpClient.execute(httpGet, new BasicHttpContext());
            }
            //结束时间
            long endTime= System.currentTimeMillis();
            logger.debug(url+"请求耗时毫秒数："+(endTime-startTime)+",换算为秒："+(endTime-startTime)/1000f);
            //处理响应码
            if (response.getStatusLine().getStatusCode() != 200) {
                logger.debug("request url failed, http code=" + response.getStatusLine().getStatusCode() + ", url=" + url);
                return null;
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String resultStr = EntityUtils.toString(entity, "utf-8");

//                JSONObject result = JSON.p(resultStr);
                return JSON.parseArray(resultStr);
//                logger.debug("request url=" + url + ",响应结果 value="+resultStr);
//                if (result.getInteger("errcode") == 0) {  //TODO 根据返回值自定义
//                    return result;
//                } else {
//                    logger.debug("request url=" + url + ",return value=");
//                    //logger.debug(resultStr);
//                    String errCode = result.getString("errcode");    //TODO 根据返回值自定义
//
//                    throw new Exception(resultStr);
//                }
            }
        } catch (IOException e) {
            logger.debug("request url=" + url + ", exception, msg=" + e.getMessage());
            e.printStackTrace();
            throw  e;
        } finally {
            if (response != null) try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }


    /**
     * 绕过验证
     *
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sc = SSLContext.getInstance("SSLv3");
        // 实现一个X509TrustManager接口，用于绕过验证，不用修改里面的方法
        X509TrustManager trustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sc.init(null, new TrustManager[] { trustManager }, null);
        return sc;
    }

    public static String getStr(String url) throws Exception {
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = MyHttpClientUtils.getHttpClient();
        RequestConfig requestConfig = RequestConfig.custom().
                setSocketTimeout(5000).setConnectTimeout(3000).build();
        httpGet.setConfig(requestConfig);
        try {
            //开始时间
            long startTime= System.currentTimeMillis();
            //执行请求
            try {
                response = httpClient.execute(httpGet, new BasicHttpContext());
            }catch (Exception e){
                logger.error("调用get请求失败{}",e.getMessage());
//                response = httpClient.execute(httpGet, new BasicHttpContext());
            }
            //结束时间
            long endTime= System.currentTimeMillis();
            logger.debug(url+"请求耗时毫秒数："+(endTime-startTime)+",换算为秒："+(endTime-startTime)/1000f);
            //处理响应码
            if (response.getStatusLine().getStatusCode() != 200) {
                logger.debug("request url failed, http code=" + response.getStatusLine().getStatusCode() + ", url=" + url);
                return null;
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                return EntityUtils.toString(entity, "utf-8");

            }
        } catch (IOException e) {
            logger.debug("request url=" + url + ", exception, msg=" + e.getMessage());
            e.printStackTrace();
            throw  e;
        } finally {
            if (response != null) try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }




    public static String getSSLStr(String url) throws Exception {
        String body = "";
        //采用绕过验证的方式处理https请求
        SSLContext sslcontext = createIgnoreVerifySSL();

        // 设置协议http和https对应的处理socket链接工厂的对象
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", new SSLConnectionSocketFactory(sslcontext))
                .build();
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        HttpClients.custom().setConnectionManager(connManager);

        //创建自定义的httpclient对象
        CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
//		CloseableHttpClient client = HttpClients.createDefault();

        //创建post方式请求对象
        HttpGet httpGet = new HttpGet(url);

        System.out.println("请求地址："+url);

        //设置header信息
        //指定报文头【Content-type】、【User-Agent】
        httpGet.setHeader("Content-type", "application/x-www-form-urlencoded");
        httpGet.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        //执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = client.execute(httpGet);
        //获取结果实体
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            //按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, "utf-8");
        }
        EntityUtils.consume(entity);
        //释放链接
        response.close();
        return body;

    }


    public static String postSSLStr(String url,Object data) throws Exception {
        String body = "";
        //采用绕过验证的方式处理https请求
        SSLContext sslcontext = createIgnoreVerifySSL();

        // 设置协议http和https对应的处理socket链接工厂的对象
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", new SSLConnectionSocketFactory(sslcontext))
                .build();
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        HttpClients.custom().setConnectionManager(connManager);

        //创建自定义的httpclient对象
        CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
//		CloseableHttpClient client = HttpClients.createDefault();

        //创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);

        StringEntity requestEntity = new StringEntity(JSON.toJSONString(data), "utf-8");
        httpPost.setEntity(requestEntity);
        //设置参数到请求对象中

        System.out.println("请求地址："+url);

        //设置header信息
        //指定报文头【Content-type】、【User-Agent】
        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        //执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = client.execute(httpPost);
        //获取结果实体
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            //按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, "GBK");
        }
        EntityUtils.consume(entity);
        //释放链接
        response.close();
        return body;

    }

    public static String postStr(String url, Object data) throws IOException {
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = MyHttpClientUtils.getHttpClient();//modify by neo 2016.10.26
        RequestConfig requestConfig = RequestConfig.custom().
                setSocketTimeout(5000).setConnectTimeout(2000).build();
        httpPost.setConfig(requestConfig);
        httpPost.addHeader("Content-Type", "application/json");

        try {
            StringEntity requestEntity = new StringEntity(JSON.toJSONString(data), "utf-8");
            httpPost.setEntity(requestEntity);

            response = httpClient.execute(httpPost, new BasicHttpContext());

            if (response.getStatusLine().getStatusCode() != 200) {

                logger.debug("request url failed, http code=" + response.getStatusLine().getStatusCode()
                        + ", url=" + url);
                return null;
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                return EntityUtils.toString(entity, "UTF-8");

            }
        } catch (IOException e) {
            logger.debug("request url=" + url + ", exception, msg=" + e.getMessage());
            e.printStackTrace();
            throw e;
        } finally {
            if (response != null) try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }


    public static void main(String[] args) throws Exception {
        JSONObject obj = new JSONObject();
        obj.put("card","6212264100011335373");
        obj.put("x","32");
        obj.put("y","24");

        String str = getStr("http://www.cardcn.com/search.php?word=6212264100011335373");
        System.err.println(str);

    }
}
